#-*-coding:utf-8-*-
import asyncio
import time
from wxpusher import WxPusher
import datetime
import json
import pymysql
from lxml import etree
import requests
import traceback
from jd_login import main
from crypt import encryptData,decryptData,getSMKey
import configparser
conf = configparser.ConfigParser()
conf.read('../config.ini')

conn = pymysql.connect(host=conf['MYSQL']['HOST'], port=int(conf['MYSQL']['PORT']), user=conf['MYSQL']['USER'], password=conf['MYSQL']['PASSWORD'], db='smp_data', charset='utf8',autocommit=True)
cur = conn.cursor()
def run():
    zhs = {
          "阳光雨露服务中心":("jd_UNmmvemPIMdn", "zyq1103."),
          # '阳光多品牌': ('18101023889', 'lenovo3c@'),
          }
    for zh in list(zhs.keys()):
         username = zhs[zh][0]
         password = zhs[zh][1]
         cookies = asyncio.get_event_loop().run_until_complete(main(zh, username, password))
         cookie = {}
         for i in cookies:
              cookie[i['name']] = i['value']
         cookie_str = ''
         for key in list(cookie.keys()):
             cookie_str += key + '='
             cookie_str += cookie[key] + ';'
         cookie_str = cookie_str[:-1]
         headers = {
             'Accept': 'application/json, text/plain, */*',
             'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
             'Connection': 'keep-alive',
             'Content-Type': 'application/json',
             'Origin': 'https://digital-ins.jd.com',
             'Referer': 'https://digital-ins.jd.com/',
             'Sec-Fetch-Dest': 'empty',
             'Sec-Fetch-Mode': 'cors',
             'cookie':cookie_str,
             'Sec-Fetch-Site': 'same-site',
             'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.49',
             'appcode': 'lvshengSP',
             'sec-ch-ua': '" Not;A Brand";v="99", "Microsoft Edge";v="103", "Chromium";v="103"',
             'sec-ch-ua-mobile': '?0',
             'sec-ch-ua-platform': '"Windows"',
             'userId': 'jd_7158c2adb6089',
            }
         # 获取查询执行shopCode_id
         shopCode_id = requests.post('https://baozang-out.jd.com/serviceOrder/queryBindShopInfo', headers=headers)
         for shop_info in shopCode_id.json()['values']:
             print('正在获取{}账号的{}店铺下的订单'.format(zh,shop_info['name']))
             shop_code = shop_info['code']
             data = {
                 "pageIndex": 1,
                 "pageSize": 500,
                 "query": {
                     "shopCode": shop_code,
                     "performingId": "",
                     "orderId": "",
                     "phone": "",
                     "serviceOrderNo": "",
                     "expressNo": "",
                     "serviceState": None,
                     "createTime": "",
                     "endTime": "",
                     "serviceOrderQueryEnum": "REPAIRING"
                 }
             }
             key = getSMKey(cookie)
             data = encryptData(key,data)
             jro_list = requests.post('https://baozang-out.jd.com/serviceOrder/queryWaitAggregation', headers=headers, data=data)
             values = jro_list.json()['result']
             values = decryptData(values)
             values = values["values"]
             # print(values)
             for value in values:
                 if value['reminderState'] == '1':
                     try:
                         if value['reminderCount'] > 0:
                             headers_wx = {
                                 'Content-Type': 'application/json'
                             }
                             data_wx = {
                                 "appToken": "AT_ZnLRyg7i63l1hUMmvVgCiyh3aRgcyvX7",
                                 "content": "催单提醒次数为{},履约单号为:{}".format(value['reminderCount'],value['performingOrderNo']),
                                 "summary": "已发现催单提醒，请及时处理",
                                 # 消息摘要，显示在微信聊天页面或者模版消息卡片上，限制长度100，可以不传，不传默认截取content前面的内容。
                                 "contentType": 1,  # 内容类型 1表示文字  2表示html(只发送body标签内部的数据即可，不包括body标签) 3表示markdown
                                 "topicIds": ['23688']
                             }
                             data_wx = json.dumps(data_wx)
                             requests.post('http://wxpusher.zjiecode.com/api/send/message', data=data_wx,headers=headers_wx)
                             print('已催单{}'.format(value['performingOrderNo']))
                     except:
                         print("无需催单{}".format(value['performingOrderNo']))



if __name__ == '__main__':
    run()
